<script lang="ts" setup>
	import { ref } from 'vue';
	import { onLoad } from "@dcloudio/uni-app"
	import { useCouponStore, useProductStore } from '@/stores';
	import { currency, calculateDistance } from '@/utils';
	import * as mapApi from '@/api/map';

	const tabIndex = ref('1')
	const couponStore = useCouponStore()
	const productStore = useProductStore()
	const products = ref<any>([])
	const coupon = ref<any>({})
	const product = ref<any>({})
	const popupVisible = ref(false)
	const acceptGouponPopupVisible = ref(false)
	const from = ref<any>({})

	onLoad(async () => {
		// 获取位置
		uni.getLocation({
			geocode: true,
			success: (res : any) => {
				from.value = {
					latitude: res.latitude,
					longitude: res.longitude,
				}
			},
			fail: (err) => {
				console.log(err)
			},
		})
		await fetchData()
	})

	async function fetchData() {
		coupon.value = await couponStore.getActivatedCoupon({
			whichDay: Number(tabIndex.value)
		})
		if (coupon.value.id) {
			const data = await productStore.getProductListByCoupon({ couponId: coupon.value.id })
			//.couponReloationProductAndMerchantAddress
			// list.forEach((item : any) => {
			// 	const { longitude, latitude } = item.merchantAddress
			// 	console.log(from.value.latitude)
			// 	console.log(from.value.longitude)
			// 	console.log(parseFloat(latitude))
			// 	console.log(parseFloat(longitude))
			// 	const duration : any = calculateDistance(from.value.latitude, from.value.longitude, parseFloat(latitude), parseFloat(longitude))
			// 	item.duration = duration.toFixed(2)
			// })
			products.value = data.couponReloationProductAndMerchantAddress
		} else {
			products.value = []
		}
	}

	function handleSelect(value : string) {
		tabIndex.value = value;
		fetchData()
	}

	async function handleProductSelect(item : any) {
		const data = await productStore.getProductByCoupon({
			couponId: coupon.value.id,
			productId: item.productId
		})
		const newProduct = data.couponReloationProductAndMerchantAddress
		product.value = { ...newProduct.couponRelationProduct, merchant: newProduct.merchantAddress }
		popupVisible.value = true
	}

	async function handleAcceptGoupon() {
		const result = await couponStore.doAcceptGoupon({ couponId: coupon.value.id })
		if (result) {
			uni.showModal({
				showCancel: false,
				title: "您已成功领取优惠券"
			})
		} else {
			uni.showModal({
				showCancel: false,
				title: "您领取优惠券数量已达上限，无法再进行领取操作"
			})
		}
		acceptGouponPopupVisible.value = false
	}

	function handleCallPhone() {
		uni.makePhoneCall({
			phoneNumber: product.value.merchant.phone
		});
	}

	function handleOpenLocation(product : any) {
		uni.openLocation({
			latitude: parseFloat(product.merchant.latitude),
			longitude: parseFloat(product.merchant.longitude),
			success: function () {
				console.log('success');
			},
			fail: function (err) {
				console.log(err)
			}
		});
	}
</script>

<template>
	<view class="page">
		<x-title-bar title="大蓝卡"></x-title-bar>
		<view class="header">
			<x-image src="/product/title.png" width="384rpx" mode="widthFix"></x-image>
			<view class="subtitle">— 用心选品，只为省心 — </view>
		</view>
		<view class="tabs">
			<view class="tab-item" :class="{' tab-item-actived':tabIndex==='1'}" @tap="handleSelect('1')">今日有折扣</view>
			<view class="tab-item" :class="{' tab-item-actived':tabIndex==='2'}" @tap="handleSelect('2')">明日有折扣</view>
		</view>
		<view class="product">
			<x-empty v-if="products.length ===0" style="margin: 100rpx auto;"></x-empty>
			<template v-else v-for="product in products" :key="product.id">
				<x-product @tap="handleProductSelect(product.couponRelationProduct)"
					:cover="product.couponRelationProduct.image" :title="product.couponRelationProduct.name">
					<x-space direction="vertical" :size="16">
						<x-space style="margin-top: 5rpx;">
							<x-text color="#999999" :size="24">{{product.duration||0}}km</x-text>
							<x-text color="#999999" :size="24">劵剩余100</x-text>
						</x-space>
						<x-space>
							<x-tag>五折</x-tag>
							<x-tag outline>领劵到店消费</x-tag>
						</x-space>
						<view class="price">
							<view class="original">
								<view>优惠前</view>
								<view>￥{{currency(product.couponRelationProduct.salesPrice, 0)}}</view>
							</view>
							<view class="now">
								<view>￥<text
										class="strong">{{currency(product.couponRelationProduct.discountedPrice)}}</text>
								</view>
								<view>到手价</view>
							</view>
						</view>
					</x-space>
				</x-product>
			</template>
		</view>
		<x-popup :visible="popupVisible" @cancel="popupVisible=false">
			<x-space direction="vertical" :size="24">
				<x-image :src="product.image" :prefix="false"></x-image>
				<x-text>{{product.name}}</x-text>
				<x-text color="#999">距离门店3.4km</x-text>
				<view style="display: flex;justify-content: space-between; align-items: center;">
					<x-space>
						<x-tag>五折</x-tag>
						<x-tag outline>领劵到店消费</x-tag>
					</x-space>
					<x-button type="primary" shape="round" @tap="handleOpenLocation(product)">去导航</x-button>
				</view>
				<x-space align="end">
					<x-text>到手价<x-text :size="40">￥{{currency(product.discountedPrice)}}</x-text></x-text>
					<x-text line-through>￥{{currency(product.salesPrice)}}</x-text>
				</x-space>
				<x-space style="margin-bottom: 16rpx;">
					<x-button style="flex:1" type="primary" shape="round" @tap="handleCallPhone">联系门店</x-button>
					<x-button style="flex:1" type="primary" shape="round"
						@tap="popupVisible=false;acceptGouponPopupVisible=true">我要领劵</x-button>
				</x-space>
			</x-space>
		</x-popup>
		<x-popup :visible="acceptGouponPopupVisible" position="center">
			<x-space direction="vertical" :size="40">
				<x-text>1. 此优惠券截止今日22:00后会失效</x-text>
				<x-text>2. 到店出示优惠券码可用折后价消费</x-text>
				<x-button type="primary" shape="round" @tap="handleAcceptGoupon">确认领券</x-button>
			</x-space>
		</x-popup>
	</view>
</template>

<style lang="scss" scoped>
	.page {
		min-height: 100vh;
		background: linear-gradient(151deg, #00A3FF 22%, #00A3FF 22%, #00CB90 51%);

		.header {
			text-align: center;
			padding-top: 40rpx;

			.subtitle {
				font-size: 32rpx;
				color: #fff;
				margin-top: 20rpx;
			}
		}

		.tabs {
			background-color: rgba(255, 255, 255, 0.5);
			display: flex;
			align-items: center;
			border-radius: 100rpx;
			margin: 72rpx 32rpx 0;
			padding: 0 6rpx;
			box-sizing: border-box;
			height: 84rpx;

			.tab-item {
				flex: 1;
				height: 72rpx;
				line-height: 72rpx;
				border-radius: 100rpx;
				text-align: center;
				color: #fff;

				&.tab-item-actived {
					background-color: #fff;
					color: #2792E2;
				}
			}
		}

		.product {
			background-color: #fff;
			min-height: 100vh;
			border-radius: 20rpx 20rpx 0 0;
			margin-top: 32rpx;
			padding: 32rpx;
			display: flex;
			flex-direction: column;
			gap: 32rpx;

			.price {
				width: 416rpx;
				height: 80rpx;
				background: url("https://static.xiaolanlk.com/dlk-mobile/product/buy-bg.png") no-repeat left top/cover;
				display: flex;
				align-items: center;

				.original {
					color: #999999;
					font-size: 24rpx;
					width: 103rpx;
					padding-left: 10rpx;
					box-sizing: border-box;
				}

				.now {
					display: flex;
					align-items: flex-end;
					line-height: 36rpx;
					gap: 10rpx;
					padding-left: 10rpx;
					padding-top: 16rpx;
					box-sizing: border-box;
					font-size: 24rpx;
					color: #FA5732;

					.strong {
						font-size: 36rpx;
					}
				}
			}
		}
	}
</style>